package com.example.iot.service.impl;

import com.aliyun.iot20180120.Client;
import com.aliyun.iot20180120.models.*;

import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.iot.mapper.aliyunDataMapper;
import com.example.iot.pojo.aliyunData;
import com.example.iot.service.aliyunDataService;
import com.example.iot.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author : Lin
 * @version : [v1.0]
 * @className : aliyunDataServiceImpl
 * @description : 描述说明该类的功能
 * @createTime : 2024/5/24 17:24
 * @updateUser : Lin
 * @updateTime : 2024/5/24 17:24
 * @updateRemark : 描述说明本次修改内容
 */
@Service
public class aliyunDataServiceImpl implements aliyunDataService {
    private String accessKeyId="LTAI5t86teCDoyGwEgQpMM7K";
    private String accessKeySecret="7Q8t0hrMIuK40PkSr0AapDCL2Fz2Zb";
    private String iotInstanceId="iot-06z00hsrrl1d98x";
    private String productKey="k0wdpss0mk0";
    private String deviceName="T_H_wife";
    private String iotId="FBTaiFTOuttmgOpxAUIDk0wdp0";
    private Client client;

    @Autowired
    private aliyunDataMapper aliyunDataMapper;
    private LambdaQueryWrapper<aliyunData> lqw;

    public aliyunDataServiceImpl() throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
// 访问的域名
        config.endpoint = "iot.cn-shanghai.aliyuncs.com";

        this.client = new Client(config);
        System.out.println("client init");


         lqw= new LambdaQueryWrapper<aliyunData>();
    }

    @Override
    public R getAliyunData() throws Exception {
        QueryDevicePropertyStatusRequest request = new QueryDevicePropertyStatusRequest();
        request.setIotInstanceId(iotInstanceId)
                .setProductKey(productKey)
                .setDeviceName(deviceName)
                .setIotId(iotId);
        try {
            QueryDevicePropertyStatusResponse response = this.client.queryDevicePropertyStatus(request);
            // response中包含服务端响应的body和headers。
            //获取本次调用requestId。
            System.out.println(response);

            //调用成功。
            if (response.getBody().getSuccess()) {
                System.out.println(response.getBody().getSuccess());
                List<QueryDevicePropertyStatusResponseBody.QueryDevicePropertyStatusResponseBodyDataListPropertyStatusInfo> datalist = response.getBody().getData().list.getPropertyStatusInfo();
                System.out.println(datalist);
                aliyunData aliyunData = new aliyunData();
                for (QueryDevicePropertyStatusResponseBody.QueryDevicePropertyStatusResponseBodyDataListPropertyStatusInfo data : datalist) {
                    System.out.println(data);
                    switch (data.name){
                        case "温度检测":aliyunData.setTemperature(Float.valueOf(data.value));
                        case "湿度检测":aliyunData.setHumidity(Float.valueOf(data.value));
                        case "空气质量指数":aliyunData.setAirQuality(Float.valueOf(data.value));
                        case "烟雾":aliyunData.setSmoke(Float.valueOf(data.value));
                        case "一氧化碳":aliyunData.setCo(Float.valueOf(data.value));
                    }
                }
                // 创建日期格式化对象
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                // 格式化日期对象为字符串
                String timestamp = sdf.format(new Date(System.currentTimeMillis()));
                aliyunData.setTimestamp(timestamp);
//                aliyunDataMapper.insert(aliyunData);
                return R.ok(aliyunData);


            } else {
                //调用失败。
                //获取调用失败错误码。
                System.out.println(response.getBody().getCode());
                //获取调用失败错误描述。
                System.out.println(response.getBody().getErrorMessage());
                return R.fail("请求失败");
            }
        } catch (TeaException error) {
            //服务端业务异常。
            System.out.println(error.getCode());
            System.out.println(error.getMessage());
            return R.fail("请求失败");
        } catch (Exception e) {
            //其他运行时异常。
            e.printStackTrace();
            return R.fail("请求失败");
        }
    }
    @Override
    public R getTemperatures(){
        lqw.clear();
        lqw.orderByDesc(aliyunData::getTimestamp);
        lqw.select(aliyunData::getTemperature,aliyunData::getTimestamp).last("LIMIT 16");
        List<aliyunData> temperatureList = aliyunDataMapper.selectList(lqw);
        HashMap<String, Object> map = new HashMap<>();
        List<Object> valuelist = Arrays.asList(temperatureList.stream().map(aliyunData::getTemperature).toArray());
        List<Object> timestamplist = Arrays.asList(temperatureList.stream().map(aliyunData::getTimestamp).toArray());
        Collections.reverse(valuelist);
        Collections.reverse(timestamplist);
        map.put("valuelist",valuelist);
        map.put("timestamplist",timestamplist);
        return R.ok(map);
    }
    @Override
    public R getDataLists(){
        lqw.clear();
        lqw.orderByDesc(aliyunData::getTimestamp);
        lqw.select(aliyunData::getTemperature,aliyunData::getTimestamp,aliyunData::getCo,aliyunData::getAirQuality).last("LIMIT 16");
        List<aliyunData> temperatureList = aliyunDataMapper.selectList(lqw);
        HashMap<String, Object> map = new HashMap<>();
        List<Object> temperaturelist = Arrays.asList(temperatureList.stream().map(aliyunData::getTemperature).toArray());
        List<Object> colist = Arrays.asList(temperatureList.stream().map(aliyunData::getCo).toArray());
        List<Object> airlist = Arrays.asList(temperatureList.stream().map(aliyunData::getAirQuality).toArray());
        List<Object> timestamplist = Arrays.asList(temperatureList.stream().map(aliyunData::getTimestamp).toArray());
        Collections.reverse(temperaturelist);
        Collections.reverse(colist);
        Collections.reverse(airlist);
        Collections.reverse(timestamplist);
        map.put("temperaturelist",temperaturelist);
        map.put("colist",colist);
        map.put("airlist",airlist);
        map.put("timestamplist",timestamplist);
        return R.ok(map);
    }
}
